package com.ustc.py.user.controller;



import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSONObject;
import com.ustc.py.storage.LoginUserLocalStorage;
import com.ustc.py.user.entity.User;
import com.ustc.py.user.service.UserService;
import com.ustc.py.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    private static final String APPID = "wxc41a28bced774b8d";
    private static final String APPSECRET = "d2c4ba6006792612637bf74cca604f6f";
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody JSONObject request) {
        String code = request.getString("code");
        JSONObject userInfo = request.getJSONObject("userInfo");
        System.out.println(userInfo.toString());
        String nickname = userInfo.getString("nickName");
        System.out.println(code+"--------"+nickname);
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", APPID, APPSECRET, code);
        User user = userService.handleLogin(url, nickname);
        LoginUserLocalStorage.setCurrentLoginUserId(user.getId());
        Map<String, Object> result = new HashMap<>();
        result.put("openId", user.getOpenId());
        result.put("msg", "登录成功");
        return R.ok(result);
    }
}
